<template>
  <!--
         packing 包装
         in 入箱
         out 取出
         record 记录
    -->
  <div class="VonPacking">
    <div class="VonPackingTop">
      <VonCrumbs :title="packingMap[packingType]" component-name="record"></VonCrumbs>
      <div class="dataBox" v-if="packingType == 'packing'">
        <!--        <VonInputBottom label="批号：" width="200px" value="11111111111"></VonInputBottom>-->
        <VonInputHorizon ref="boxNo" label="箱码：" width="300px" v-model="form.boxNo" @keyup.enter.native="getBoxCode">
        </VonInputHorizon>
        <VonInputBottom label="箱子容量：" width="200px" v-model="form.boxCapacity"></VonInputBottom>
        <VonInputHorizon ref="productBarCode" label="条码/二维码：" width="600px" v-model="form.productBarCode"
          @keyup.enter.native="getProductBarCode"></VonInputHorizon>
        <div class="miniButtonBox">
          <el-button type="primary" size="mini" class="miniButton" @click.stop="packageData()">包装</el-button>
          <el-button type="danger" size="mini" class="miniButton" @click.stop="delData()">清空</el-button>
        </div>
      </div>
      <div class="dataBox" v-if="packingType == 'in'">
        <VonInputHorizon ref="boxNo" label="箱码：" width="300px" v-model="form.boxNo" @keyup.enter.native="getBoxCode">
        </VonInputHorizon>
        <VonInputBottom label="容量：" width="200px" v-model="form.boxCapacity"></VonInputBottom>
        <VonInputHorizon ref="productBarCode" label="条码/二维码：" width="600px" v-model="form.productBarCode"
          @keyup.enter.native="getProductBarCode"></VonInputHorizon>
        <div class="miniButtonBox">
          <el-button type="primary" size="mini" class="miniButton" @click.stop="intoBoxData()">入箱</el-button>
          <el-button type="danger" size="mini" class="miniButton" @click.stop="delData()">清空</el-button>
        </div>
      </div>
      <div class="dataBox" v-if="packingType == 'out'">
        <VonInputHorizon ref="productBarCode" label="条码/二维码：" width="600px" v-model="form.productBarCode"
          @keyup.enter.native="getProductBarCode"></VonInputHorizon>
        <div class="miniButtonBox">
          <el-button type="primary" size="mini" class="miniButton" @click.stop="removeBoxData()">取出</el-button>
          <el-button type="danger" size="mini" class="miniButton" @click.stop="delData()">清空</el-button>
        </div>
      </div>
      <div class="dataBox" v-if="packingType == 'record'">
        <VonInputHorizon label="出库单：" width="300px" v-model="searchOrderNo"></VonInputHorizon>
        <VonInputHorizon label="产品SN码：" width="300px" v-model="searchProductSn"></VonInputHorizon>
        <span class="span-title">产品名称：</span>
        <VonSelect width="200px" v-model="searchRecipeId" :options="options"></VonSelect>
        <VonInputHorizon label="批次：" width="300px" v-model="searchBatchNo"></VonInputHorizon>
        <VonInputHorizon label="箱码：" width="300px" v-model="searchBoxNo"></VonInputHorizon>
        <div class="miniButtonBox">
          <el-button type="primary" size="mini" class="miniButton" @click.stop="searchBoxData()">查询</el-button>
          <el-button type="danger" size="mini" class="miniButton" @click.stop="seldownBoxData()">选中下载
          </el-button>
          <el-button type="danger" size="mini" class="miniButton" @click.stop="downBoxData()">下载全部
          </el-button>
        </div>
      </div>
    </div>
    <div class="VonPackingBottom VonPackingBottomRecord" v-if="packingType == 'record'">
      <VonTable ref="pageTable" :column="sel_column" :tableData="tablePageData" showPagination selection height="400px"
        :total="total" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange">
        <template slot="num">
          <el-table-column label="序号" align="center" width="100px">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </VonTable>
    </div>
    <div class="VonPackingBottom" v-else>
      <div class="VonPackingBottomLeft">
        <div class="showContent">
          <p class="showContent1">工单号：</p>
          <VonInput width="230px" style="margin: 0" v-model="form.orderNo"></VonInput>
        </div>
        <div class="showContent">
          <p class="showContent1">产品料号：</p>
          <p class="showContent2">{{ form.productName }}</p>
        </div>
        <div class="line"></div>
        <div class="BigNumber">{{ bigNumber }}</div>
      </div>
      <div class="VonPackingBottomRight">
        <VonTable :column="column" :tableData="tableData">
          <template slot="num">
            <el-table-column label="序号" align="center" width="100px">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
          <el-table-column slot="operation" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="color: #1890ff" @click.stop="remove(scope.$index)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </VonTable>
      </div>
    </div>
    <VonDialog @commitResult="commitResult_Bad" @cancelResult="cancelResult_Bad" :isShow_Popup="isShow_Popup_Bad"
      :isShowCancelButton="false" successText="确定" cancelText="" title="注意">
      <div slot="content">
        <div class="warningBox">
          <div style="text-align: center">
            <img src="../../assets/workStation/warningBox.png" alt="">
            <div class="title_warning">{{ this.dialogMsg }}</div>
          </div>
        </div>
      </div>
    </VonDialog>
  </div>
</template>

<script>
import {
  getip,
  getProductOrderBarcode,
  getPackageNum,
  createProductOutStock,
  addProductOutStockdetail,
  removeProductOutStockdetail,
  getProductOutStockDetailPageList,
  exportProductOutStockList,
  exportSelProductOutStockList,
  getJudgeState
} from "../../api/workStation/handle";
import { getRecipeOptions } from "../../api/workStation/mainControl";
import { openLoading, closeLoading } from "../../common/prompt";

export default {
  name: "VonPacking",
  data() {
    return {
      packingMap: {
        packing: "扫码包装",
        in: "扫码入箱",
        out: "扫码取出",
        record: "查询记录",
      },
      column: [
        {
          align: "center",
          label: "产品条形码",
          prop: "productBarCode",
        },
      ],
      sel_column: [
        {
          align: "center",
          label: "SN码",
          prop: "productSn",
        },
        {
          align: "center",
          label: "箱码",
          prop: "boxNo",
        },
        {
          align: "center",
          label: "产品代码",
          prop: "productCode",
        },
        {
          align: "center",
          label: "批次",
          prop: "batchNo",
        },
      ],
      tableData: [],
      tablePageData: [],
      options: [],
      form: {},
      isShow_Popup_Bad: false,
      dialogMsg: "",
      searchOrderNo: "",
      searchBatchNo: "",
      searchBoxNo: "",
      searchProductSn: "",
      searchProductCode: "",
      searchRecipeId: "",
      pageIndex: 1,
      pageSize: 20,
      total: 0,
    };
  },
  mounted() {
    if (this.packingType === "out")
      this.$refs.productBarCode.$children[0].focus();
    else if (this.packingType === "record") { }
    else this.$refs.boxNo.$children[0].focus();
  },
  created() {
    this.getOptions();
  },
  props: {
    packingType: {
      type: [Number, String],
      default: "1",
    },
  },
  methods: {
    commitResult_Bad() {
      this.isShow_Popup_Bad = false;
    },
    cancelResult_Bad() {
      this.isShow_Popup_Bad = false;
    },
    handleCurrentChange(value) {
      this.pageIndex = value;
      this.pageBoxData();
    },
    handleSizeChange(value) {
      this.pageSize = value;
      this.pageBoxData();
    },
    remove(index) {
      this.tableData.splice(index, 1);
    },
    getOptions() {
      getRecipeOptions().then((res) => {
        this.options = res.data;
      });
    },
    getBoxCode() {
      if (this.form.boxNo == "" || this.form.boxNo == undefined) return;
      openLoading();
      getPackageNum().then((res) => {
        closeLoading();
        if (res.status == 200) {
          this.$refs.productBarCode.$children[0].focus();
          this.form = {
            boxNo: this.form.boxNo,
            productName: res.data.productName,
            boxCapacity: res.data.num,
            productBarCode: "",
            orderNo: "",
          };
        } else {
          this.$message.error(res.error.message);
        }
      });
    },
    getProductBarCode(value) {
      debugger;
      if (this.form.productBarCode == "" || this.form.productBarCode == undefined)
        return;
      if (this.packingType != "out" && (this.form.boxCapacity == "" || this.form.boxCapacity == undefined)) {
        this.dialogMsg = "请先扫入箱码";
        this.isShow_Popup_Bad = true;
        return;
      }
      var that = this;
      var exist_code = this.tableData.filter(function (item) {
        return item.productBarCode == that.form.productBarCode;
      })
      if (exist_code.length > 0) {
        this.dialogMsg = "请不要重复扫入";
        this.isShow_Popup_Bad = true;
        return;
      }
      var data = {
        BoxNo: this.form.boxNo,
        BoxCapacity: this.form.boxCapacity,
        ProductBarCode: this.form.productBarCode
      }
      if (this.packingType != "out") {
        getJudgeState(data).then((res) => {
          if (res.status == 200 || res.status == 204) {
            debugger;
            if (res.data != "OK") {
              this.dialogMsg = res.data;
              this.isShow_Popup_Bad = true;
              return;
            }
          }
          else {
            this.dialogMsg = "扫码失败";
            this.isShow_Popup_Bad = true;
            return;
          }
          this.getDataList();
          this.form.productBarCode = "";
        });
      }
      else {
        this.getDataList();
        this.form.productBarCode = "";
      }
    },
    packageData() {
      if (this.form.boxCapacity == "" || this.form.boxCapacity == undefined) {
        this.dialogMsg = "箱子容量不能为空,由箱码回车带入";
        this.isShow_Popup_Bad = true;
        return;
      }
      if (this.form.orderNo == "" || this.form.orderNo == undefined) {
        this.dialogMsg = "请输入工单号";
        this.isShow_Popup_Bad = true;
        return;
      }
      if (this.tableData.length == 0) {
        this.dialogMsg = "扫入二维码数目最少为一条";
        this.isShow_Popup_Bad = true;
        return;
      }
      var detailList = [];
      for (var i = 0; i < this.tableData.length; i++) {
        detailList.push({ productOrderId: this.tableData[i].id });
      }
      var data = {
        title: {
          orderNo: this.form.orderNo,
          batchNo: this.form.boxNo.slice(1, 14),
          boxNo: this.form.boxNo,
          boxCapacity: this.form.boxCapacity.toString(),
          productDate: this.form.boxNo.slice(1, 9),
        },
        details: detailList,
      };
      createProductOutStock(data).then((res) => {
        if (res.status == 200 || res.status == 204) {
          this.$message.success("包装成功");
          this.tableData = [];
          this.form = {};
        } else {
          this.$message.error("包装失败");
        }
      });
    },
    delData() {
      this.tableData = [];
      /*    for (var i = 0; i < this.tableData.length; i++) {
           if (this.tableData[i].productBarCode == this.form.productBarCode) {
             this.tableData.splice(i, 1);
           }
         } */
    },
    intoBoxData() {
      if (this.form.boxCapacity == "" || this.form.boxCapacity == undefined) {
        this.dialogMsg = "箱子容量不能为空,由箱码回车带入";
        this.isShow_Popup_Bad = true;
        return;
      }
      if (this.form.orderNo == "" || this.form.orderNo == undefined) {
        this.dialogMsg = "请输入工单号";
        this.isShow_Popup_Bad = true;
        return;
      }
      if (this.tableData.length == 0) {
        this.dialogMsg = "扫入二维码数目最少为一条";
        this.isShow_Popup_Bad = true;
        return;
      }
      var detailList = [];
      for (var i = 0; i < this.tableData.length; i++) {
        detailList.push({ productOrderId: this.tableData[i].id });
      }
      var data = {
        orderNo: this.form.orderNo,
        boxCapacity: this.form.boxCapacity.toString(),
        details: detailList,
      };
      addProductOutStockdetail(data).then((res) => {
        if (res.status == 200 || res.status == 204) {
          this.$message.success("入箱成功");
          this.tableData = [];
          this.form = {};
        } else {
          this.$message.error("入箱失败");
        }
      });
    },
    removeBoxData() {
      if (this.form.orderNo == "" || this.form.orderNo == undefined) {
        this.dialogMsg = "请输入工单号";
        this.isShow_Popup_Bad = true;
        return;
      }
      if (this.tableData.length == 0) {
        this.dialogMsg = "扫入二维码数目最少为一条";
        this.isShow_Popup_Bad = true;
        return;
      }
      var detailList = [];
      for (var i = 0; i < this.tableData.length; i++) {
        detailList.push({ productOrderId: this.tableData[i].id });
      }
      var data = {
        orderNo: this.form.orderNo,
        details: detailList,
      };
      removeProductOutStockdetail(data).then((res) => {
        if (res.status == 200 || res.status == 204) {
          this.$message.success("取出成功");
          this.tableData = [];
          this.form = {};
        } else {
          this.$message.error("取出失败");
        }
      });
    },
    searchBoxData() {
      this.pageIndex = 1;
      this.pageBoxData();
    },
    pageBoxData() {
      const params = {
        orderNo: this.searchOrderNo,
        batchNo: this.searchBatchNo,
        boxNo: this.searchBoxNo,
        productSn: this.searchProductSn,
        recipeId: this.searchRecipeId == "" ? null : this.searchRecipeId,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
      };
      openLoading();
      getProductOutStockDetailPageList(params).then((res) => {
        closeLoading();
        if (res.status == 200) {
          this.tablePageData = res.data.items;
          this.total = res.data.totalCount;
        } else {
          this.$message.error(res.error.message);
        }
      });
    },
    seldownBoxData() {
      let currentSelect = this.$refs.pageTable.$refs.VonTable.selection;
      var data = [];
      for (let item in currentSelect) {
        data.push(currentSelect[item]);
      }
      openLoading();
      exportSelProductOutStockList(data).then((res) => {
        closeLoading();
        if (res.status != 200) {
          this.$message.error(res.error.message);
        } else {
          //fileName:下载的文件名
          var fileName = decodeURIComponent(
            res.headers["content-disposition"].split("=")[1]
          );
          let blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
          });

          // 针对ie浏览器
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            //非ie浏览器
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //常见下载的链接
            downloadElement.href = href;
            downloadElement.download = fileName; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放blob对象
          }
        }
      });
    },
    downBoxData() {
      const params = {
        orderNo: this.searchOrderNo,
        batchNo: this.searchBatchNo,
        boxNo: this.searchBoxNo,
        productSn: this.searchProductSn,
        recipeId: this.searchRecipeId == "" ? null : this.searchRecipeId,
      };
      openLoading();
      exportProductOutStockList(params).then((res) => {
        closeLoading();
        if (res.status != 200) {
          this.$message.error(res.error.message);
        } else {
          //fileName:下载的文件名
          var fileName = decodeURIComponent(
            res.headers["content-disposition"].split("=")[1]
          );
          let blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
          });

          // 针对ie浏览器
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            //非ie浏览器
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //常见下载的链接
            downloadElement.href = href;
            downloadElement.download = fileName; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放blob对象
          }
        }
      });
    },
    getDataList() {
      const params = {
        filter: this.form.productBarCode,
      };
      openLoading();
      getProductOrderBarcode(params).then((res) => {
        let that = this.tableData;
        closeLoading();
        if (res.status == 200) {
          if (that.length == 0) this.tableData = [res.data];
          else {
            that.push(res.data);
            this.tableData = that;
          }
        } else {
          this.$message.error(res.error.message);
        }
      });
    },
  },
  computed: {
    bigNumber() {
      return this.tableData && this.tableData.length > 0
        ? this.tableData.length
        : 0 || 0;
    },
  },
};
</script>

<style scoped lang="scss">
.warningBox {
  width: 560px;
  height: 275px;
  background: rgba(152, 166, 197, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;

  .title_warning {
    height: 49px;
    font-size: 50px;
    margin-top: 40px;
    font-family: Source Han Sans CN;
    font-weight: bold;
    color: #b9c5dd;
    line-height: 60px;
  }
}

.VonPacking {
  width: 100%;
  height: 100%;

  .VonPackingTop {
    width: 100%;
    height: 180px;
    background: linear-gradient(-30deg,
        rgba(67, 85, 110, 0.5),
        rgba(48, 47, 67, 0.5));
    border-radius: 10px;
    margin-bottom: 20px;

    .dataBox {
      display: flex;
      flex-wrap: wrap;

      .miniButtonBox {
        padding-top: 15px;

        .miniButton {
          width: 80px;
          margin: 0 10px;
          height: 40px;
        }
      }

      .span-title {
        width: 80px;
        padding-top: 18px;
        color: white;
      }
    }
  }

  .VonPackingBottomRecord {
    padding: 0 10px;
    height: 472px;
    width: 100%;
    background: linear-gradient(-30deg,
        rgba(67, 85, 110, 0.5),
        rgba(48, 47, 67, 0.5));
    border-radius: 10px;
  }

  .VonPackingBottom {
    display: flex;
    height: 472px;

    .VonPackingBottomLeft {
      width: 300px;
      height: 472px;
      background: linear-gradient(-30deg,
          rgba(67, 85, 110, 0.5),
          rgba(48, 47, 67, 0.5));
      border-radius: 10px;
      margin-right: 20px;
      padding: 30px;

      .showContent {
        .showContent1 {
          height: 16px;
          font-size: 16px;
          font-weight: 400;
          color: #feffff;
          line-height: 40px;
          margin-bottom: 20px;
        }

        .showContent2 {
          height: 20px;
          font-size: 24px;
          font-weight: bold;
          color: #00fffb;
          line-height: 40px;
          margin-bottom: 30px;
        }
      }

      .line {
        width: 260px;
        height: 2px;
        margin: 50px 0;
        background: #767e97;
        border-radius: 1px;
      }

      .BigNumber {
        margin: 0 auto;
        width: 31px;
        height: 47px;
        line-height: 47px;
        font-size: 60px;
        font-weight: bold;
        color: #ffffff;
      }
    }

    .VonPackingBottomRight {
      padding: 10px;
      flex: 1;
      height: 472px;
      background: linear-gradient(-30deg,
          rgba(67, 85, 110, 0.5),
          rgba(48, 47, 67, 0.5));
      border-radius: 10px;
    }
  }
}
</style>
